package com.shimao.celnet.payment.controller.api;

import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCUPUser;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.model.PPayDetail;
import com.shimao.celnet.payment.model.request.CallIn_OutPayReqInRequest;
import com.shimao.celnet.payment.model.request.Payment;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.*;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 银联支付申请接口
 * 外部系统 → 支付系统，数据：支付申请数据
 * Created by galen on 2018/11/21.
 */
@RestController
@RequestMapping(value = "/payment")
@Api("接口：pay-204(银联)-外部支付申请<OutPayApplyAgreeReqIn> 外部系统 → 支付系统，数据：支付申请数据")
public class CallI_OutPayApplyAgreeReqInController {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @Autowired//支付申请
    private PPayService pPayService;

    @Autowired//房间
    private BHouseService bHouseService;

    @Autowired//小区
    private BEstateService bEstateService;

    @Autowired //商家
    private PPayBusinessService pPayBusinessService;

    @Autowired
    private ConstantConfig constantConfig;

    @RequestMapping(value = "/payApplyAgreeReq",method = RequestMethod.POST)
    public String payApplyAgreeReq(@RequestBody @Valid CallIn_OutPayReqInRequest requestJson, BindingResult result){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        logger.info("pay-204-外部支付申请<OutPayApplyAgreeReqIn>请求JSON:" + requestJson.toString());
        //通过valid验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        PPay pPay = new PPay();
        String payGuid = pPayService.getGuid();
        pPay.setGuid(payGuid);
        pPay.setCreatedUserGuid(FinalUtil.INTER_FACE_USER_ID);
        pPay.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
        pPay.setBusinessType(requestJson.getpOrderType());    //	业务类型
        pPay.setPayType(FinalUtil.CUP_PAY_TYPE);             //支付方式： A03快捷支付
        pPay.setPayAmount(requestJson.getpMoney());    //	支付金额
        pPay.setPayStartTime(String.valueOf(System.currentTimeMillis()));//	支付开始时间
        if(requestJson.getEstateId() != null && requestJson.getEstateId()!= ""){
            if(bEstateService.getBySfGuid(requestJson.getEstateId()) != null){
                pPay.setEstateGuid(bEstateService.getBySfGuid(requestJson.getEstateId()).getGuid());    //	小区guid
                pPay.setEstateSfGuid(requestJson.getEstateId());    //	小区SF-GUID
            }else {
                pPay.setEstateGuid(pPayBusinessService.getByGuid(requestJson.getEstateId()).getGuid());
                pPay.setEstateSfGuid(requestJson.getEstateId());    //	小区SF-GUID
            }
        }
        if(requestJson.getHouseId() != null && requestJson.getHouseId()!= ""){
            if(requestJson.getEstateId() == "" || requestJson.getEstateId() == null){
                pPay.setEstateGuid(bHouseService.getBySfGuid(requestJson.getHouseId()).getEstateGuid());
            }
            pPay.setHourceGuid(bHouseService.getBySfGuid(requestJson.getHouseId()).getGuid());    //	支付房间guid
        }
        pPay.setHourceSfGuid(requestJson.getHouseId());    //	支付房间SF-GUID
        pPay.setPayUserSfGuid(requestJson.getMeruserid());    //	支付用户SF-GUID
        pPay.setPayUserName(requestJson.getUserName());    //	支付用户名称
        pPay.setPayRemark(requestJson.getpRemark());       //	支付说明
        pPay.setAppKey(request.getHeader(FinalUtil.HEADER_APP_KEY));//app_key
        pPay.setInterfaceId(request.getHeader(FinalUtil.HEADER_INTERFACE_ID));//接口id
        List<Payment> paymentList = requestJson.getPaymentList();
        List<PPayDetail> pPayDetailList = new ArrayList<PPayDetail>();
        for (Payment payment : paymentList) {
            PPayDetail pPayDetail = new PPayDetail();
            pPayDetail.setExsysDetailId(payment.getReceivableId());//外部系统明细id
            pPayDetail.setAmount(payment.getTotalReceivableAmount());//明细金额
            pPayDetail.setRemark(payment.getbRemark());//明细说明
            //支付申请记录明细保存
            pPayDetailList.add(pPayDetail);
        }
        //根据用户号和协议编码获取注册信息
        PPayCUPUser payCUPUser = pPayCupUserService.findCUPUserByMeruseridAndAgreeid(requestJson.getMeruserid(),requestJson.getAgreeid());
        if(payCUPUser == null){
            retJson = new ResponseJson(ErrorInfoEnum.ERROR_PARAMS, "meruserid/agreeid");
            return retJson.toString();
        }
        //根据注册信息的商户id获取商户信息
        PPayCust payCust = getTLMessage(payCUPUser.getPayCustid(), FinalUtil.CUP_PAY_TYPE);
       try {
           //请求通联申请支付
           logger.info("==================请求通联申请支付开始=====================");
           logger.info("========订单号："+pPay.getGuid() +"=========商户号："+payCust.getCustId());
           Map<String, String> map = callOut_tlPublicService.payapply(MyDateUtil.NotString(payGuid),requestJson.getAgreeid(),pPay.getPayAmount(),pPay.getBusinessType(),pPay.getPayRemark(),constantConfig.getTlReturnURL(),payCust);
           logger.info("========通联响应参数："+map.toString());
           if ("SUCCESS".equals(map.get(FinalUtil.RETCDE))){
               retJson.setErrorMessage(map.get(FinalUtil.ERRMSG));
               retJson.addBody(FinalUtil.TRXSTATUS,map.get(FinalUtil.TRXSTATUS));
               retJson.addBody("chnltrxid",map.get("chnltrxid"));
               retJson.addBody("trxid",map.get("trxid"));
               retJson.addBody(FinalUtil.THPINFO,map.get(FinalUtil.THPINFO));
               retJson.addBody("paymentId",payGuid);
               payCUPUser.setPayThpinfo(map.get(FinalUtil.THPINFO));
               pPay.setTrxid(map.get("trxid"));
               if (map.get("fintime") != null){
                   pPay.setPayEndTime(String.valueOf(new SimpleDateFormat("yyyyMMddHHmmss").parse(map.get("fintime")).getTime()));
               }
               if("0000".equals(map.get(FinalUtil.TRXSTATUS))){
                   pPay.setPayStatus(FinalUtil.PAY_STATUS_SUSCSS);
               }else if(!"1999".equals(map.get(FinalUtil.TRXSTATUS))&&!"2000".equals(map.get(FinalUtil.TRXSTATUS))&&!"2008".equals(map.get(FinalUtil.TRXSTATUS))&&!"0000".equals(map.get(FinalUtil.TRXSTATUS))){
                   pPay.setPayStatus(FinalUtil.PAY_STATUS_FAILUE);
               }
           }else {
               pPay.setPayStatus(FinalUtil.PAY_STATUS_FAILUE);
               retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, "FAIL");
           }
       }catch (Exception e){
           e.printStackTrace();
           logger.debug("通联异常参数：" + e.getMessage());
           retJson = new ResponseJson(ErrorInfoEnum.PAY_RESULT_TYPE, e.getMessage());
       }finally {
           //支付申请记录保存
           pPayService.save(pPay,pPayDetailList);
           pPayCupUserService .update(payCUPUser);
           //返回结果
           return retJson.toString();
       }
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid, String payType) {
        return pPayCustService.getBySfGuid1(estateGuid, payType);
    }

}
